define(function (require, exports, module) {
    require("apps/lab/page.css");
    require("apps/grid");
    require("apps/easyui");
    require("apps/select");

    exports.init = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid);
        page.getJqDom("accordion").accordion();
        page.getJqDom("accordion").find(".panel-tool").hide();
        var events = {
            goSelect:function(){
                page.getJqDom("accordion").accordion("select", "选择工件");
            },
            gotoParam:function(){
                var totalP = page.getJqDom("total");
                if(page.getJqDom("tool-box").children().length ||
                    (totalP.is(":visible") && totalP.html() != '0')){
                    page.getJqDom("accordion").accordion("select", "填写实验参数");
                }else{
                    $.messager.alert("提示", "请至少选择一个需要记录实验参数的工件");
                    return;
                }
            },
            cancel:function(){
                window.location.href = ctx + "/app/api/ebom/index";
            },
            save:function(){
                var ids = [];
                page.getJqDom("tool-box").children(".ebom-item").each(function () {
                    ids.push($(this).attr("data-item"));
                });
                if(ids.length > 0){
                    saveData({
                        ids: ids
                    })
                }else{
                    var t =  page.getJqDom("total").html();
                    var title = "您没有选择具体的工件，系统默认将对所有工件进行工艺参数记录，是否继续操作?"
                    if(t.length > 0){
                        title =  "您没有选择具体的工件，系统默认将对匹配条件"+ page.getJqDom("total").html()
                            +"个工件进行工艺参数记录，是否继续操作?";
                    }
                    var v = page.getJqDom("hiddenTextArea").val();
                    $.messager.confirm("选择", title, function(arg){
                        if(arg){
                            var form = v.length > 0 ? JSON.parse(v) : {};
                            saveData(form);
                        }
                    });
                }
            }
        };
        page.getJqDom("btn").linkbutton({
            onClick:function(e){
                var type = $(this).attr("data-type");
                events[type].call(this);
            }
        });
        var pageListComponent = new $.PageListComponent(uuid, {
            view: {
                grid: "grid",
                colbar: "user_list_btn"
            },
            configs: {
                gridUrl: ctx + "/app/api/lab/relative?tProcessTemplate.id=" + config.processId,
                idField: "id",
                gridColumns: [
                    {
                        field: 'id',
                        hidden: true,
                        checkbox: false
                    },
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'result',
                        title: '结果',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: 'operator',
                        hidden: true,
                        title: '记录人',
                        width: 100,
                        align: 'left'
                    }
                ]
            },
            events: {
                renderColBarBefore: function (key, row) {
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "view":
                            whenView(context, row);
                            break;
                        case "use":
                            whenUse(context, row);
                            break;
                        default :
                            break;
                    }
                }
            }
        });

        function whenView(context, row) {
            context.detail("工艺设计结构详情查看", row);
        }

        var cacheInfo = {};

        function whenUse(context, row) {
            if (cacheInfo[row.id]) {
                useTo(cacheInfo[row.id]);
            } else {
                $.getJSON(ctx + "/app/api/lab/getRecordInfo", {id: row.id}, function (data) {
                    cacheInfo[row.id] = data;
                    useTo(data);
                });
            }
        }

        var typeValueSet = {
            FIELD_TYPE_TIME:function(input, value){
                if(/\d{4}(-\d\d){2}(\S\d{2}(:\d\d){2})?/.test(value)){
                    input.datetimebox("setValue", value);
                }else{
                    input.datetimebox("setValue", "");
                }
            },
            FIELD_TYPE_TEXTAREA:function(input, value){
                input.val(value);
            },
            FIELD_TYPE_DIRECTORY:function(input, value){
                input.combobox("select", value)
            },
            FIELD_TYPE_TEXT:function(input, value){
                input.val(value);
            },
            FIELD_TYPE_NUM:function(input, value){
                if(/[\+\-]?\d+.?\d*/.test(value)){
                    input.numberbox("setValue", value);
                }else{
                    input.numberbox("setValue", "");
                }
            },
            FIELD_TYPE_ATTACHMENT:function(input, value){
                input.removeAttr("data-name");
                input.val("");
                input.prev().empty();
                if(value && value.lastIndexOf(".") > -1){
                    input.fileupload("addFile", "", value);
                }
            },
            FIELD_TYPE_SCIENTIFIC:function(input, value){
                if(/[\+\-]?\d+,\d+/.test(value)){
                    var vv = value.split(",");
                    input.eq(0).numberbox("setValue", vv[0]);
                    input.eq(1).numberbox("setValue", vv[1]);
                }else{
                    input.numberbox("setValue", "");
                }
            },
            FIELD_TYPE_TABLE:function(input, value){
                if(value){
                    input.replaceWith(value);
                }
            }
        };

        function useTo(data) {
            page.getJqDom("result").val(data.result);
            var per = data.tProcessParameters;
            if (per && per.length > 0) {
                page.getJqDom("table-form").find("input[name=fieldName]").each(function () {
                    var parentTr = $(this).closest("tr");
                    var name = $(this).val(), type = parentTr.find("[name=fieldType]").val();
                    for (var i = 0, l = per.length; i < l; i++) {
                        if (per[i].fieldName == name && per[i].fieldType == type) {
                            typeValueSet[type](parentTr.find("[data-id=f-component]"), per[i].parameterValue)
                            break;
                        }
                    }
                });
            }
        }

        page.getJqDom("operateTime").datetimebox({
            editable: false,
            required:true,
            value:new Date().format("yyyy-MM-dd hh:mm:ss")
        });
        var href = page.getJqDom("panelA").attr("data-href");
        page.getJqDom("panelA").panel({
            href: href + "&uuid=" + $.utils.createUUID(6),
            title: "系统录入数据",
            collapsible: true,
            collapsed: false
        });
        var globalWindow = new $.PageWindow();
        page.getJqDom("showCon").linkbutton({
            onClick:function(){
               var formStr = page.getJqDom("hiddenTextArea").val();
               var api = require("apps/lab/select-view");
                api.createDialog(ctx, {
                    formStr:formStr
                })
            }
        });
        var href2 = page.getJqDom("panelB").attr("data-href");
        page.getJqDom("panelC").panel({
            title: "实验基础信息",
            collapsible: true
        });
        page.getJqDom("panelB").panel({
            href: href2 + "&uuid=" + $.utils.createUUID(6),
            title: "实验采集数据",
            collapsible: true,
            onExpand:function(){
                page.getJqDom("experFrom").find(".easyui-validatebox").validatebox();
            }
        });
        page.getJqDom("same-ebom").panel({
            title: "其他实验记录",
            collapsible: true,
            collapsed: false
        });
        function resize(){
            page.getJqDom("accordion").accordion("resize");
            page.getJqDom("panelA").add(page.getJqDom("panelB")).add(page.getJqDom("panel-box"))
                .add(page.getJqDom("panelC")).add(page.getJqDom("same-ebom")).panel("resize");
        }
        $("#globContent").on("resize", function () {
            resize();
        });
        $(window).on("resize", function () {
            resize();
        });

        page.getJqDom("addTool").linkbutton({
            onClick: function () {
                whenChoose(pageListComponent);
            }
        });
        page.getJqDom("ebom-item").find("a").linkbutton({
            onClick: function () {
                $(this).closest(".ebom-item").fadeOut(function () {
                    $(this).remove();
                });
            }
        });
        page.getJqDom("chooseUser").gridSelect({
            textbox:page.getJqDom("innerUser"),
            href:ctx + "/app/api/sysMember/choose",
            method:"choose_users",
            title:"选择用户",
            setValue:function(users){
                var results = this.options.textbox.html().split(",");
                for (var i = 0, l = users.length; i < l; i++) {
                    if (!results.contains(users[i].userName)) {
                        results.push(users[i].userName)
                    }
                }
                this.options.textbox.html(results.join(","));
            }
        });

        var template = '{{#.}}<div data-id="ebom-item" class="ebom-item" data-item="{{id}}">' +
            '<div class="float-right">' +
            '<a href="javascript:void(0)" iconCls="fa fa-trash fa-lg" plain="true"></a>' +
            '</div>' +
            '<span>名称/编码：</span>{{eName}}{{code}}</div>{{/.}}';

        function whenChoose() {
            globalWindow.create({
                href: ctx + "/app/api/ebom/choose",
                method: "choose_ebom_child",
                title: "选择已发布的结构",
                width: 800,
                callback: function (status, json) {
                    if (status) {
                        var postData = json.postData;
                        page.getJqDom("total").html(json.total);
                        if(postData.length){
                            //检查是否已经包含该结构
                            var results = [], items = [];
                            page.getJqDom("ebom-item").each(function () {
                                results.push($(this).attr("data-item"));
                            });
                            for (var i = 0, l = postData.length; i < l; i++) {
                                if (!results.contains(postData[i].id)) {
                                    items.push(postData[i]);
                                }
                            }
                            $(Mustache.render(template, items)).prependTo(page.getJqDom("tool-box")).each(function () {
                                $(this).find("a").linkbutton({
                                    onClick: function () {
                                        $(this).closest(".ebom-item").fadeOut(function () {
                                            $(this).remove();
                                        });
                                    }
                                });
                            });
                            page.getJqDom("hiddenTextArea").val("");
                            page.getJqDom("showALl").hide();
                        }else{
                            page.getJqDom("tool-box").children(".ebom-item").remove();
                            page.getJqDom("hiddenTextArea").val(json.total ? json.formData : "");
                            if(json.total > 0){
                                page.getJqDom("showALl").show();
                            }
                        }
                    }
                }
            });
            globalWindow.open();
        }

        function saveData(ebom) {
            //获取基础数据
            var baseRecordForm = page.getJqDom("baseRecord");
            if (!baseRecordForm.form("validate")) {
                return false;
            }
            var baseData = baseRecordForm.serializeJson();
            baseData.tProcessParameters = [];
            page.getJqDom("panelA").find("tr.hydra-tr-bg").each(function () {
                var params = $(this).serializeJson();
                if(params.fieldType == 'FIELD_TYPE_TABLE'){
                    params.parameterValue = $(this).find("[data-id=f-component]").prop("outerHTML");
                }
                baseData.tProcessParameters.push(params);
            });
            if(config.hasDevice && config.hasDevice == "1"){
                baseData.tExperimentalData = page.getJqDom("experFrom").serializeJson();
                if(!baseData.tExperimentalData.id){
                    $.messager.alert("提示", "该实验含有外部设备实验数据，请采集数据以后再次提交。", "info");
                    page.getJqDom("panelB").panel("expand");
                    return;
                }
            }
            ebom = $.extend({}, ebom, baseData, true);
            $("body").wait("start", "工艺参数保存中，请稍后！");
            $.post(ctx + "/app/api/lab/saveProcessData", $.utils.buildJson(ebom), function (data) {
                $("body").wait("end");
                if ($.isPlainObject(data) && data.error) {
                    $.messager.alert('信息',
                        data.msg, 'info');
                } else {
                    $.messager.alert('信息',
                        "实验数据保存成功!", 'info');
                    window.location.href = ctx + "/app/api/ebom/index";
                }
            }, "JSON");
        }
    }


});